/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */ 

package tests;

/*
 * GridBagLayoutDemo.java requires no other files.
 */

import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import database.DB_connection;

public class layoutTesting {
	final static boolean shouldFill = true;
	final static boolean shouldWeightX = true;
	final static boolean RIGHT_TO_LEFT = false;
	private static int currentCol = 0;
	private static Container cPane;
	private static JFrame frame;
	private static DB_connection conn;



	//A collection of all exercise textfields created
	private static ArrayList <JTextField>exerciseFields = new ArrayList<JTextField>();
	//A collection of all weight type textfields created
	private static ArrayList <JTextField>weightTypeFields = new ArrayList<JTextField>();

	private static void newExerciseButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                  
		System.out.println("Create another line of text fields for user input.");  
		GridBagConstraints c = new GridBagConstraints();

		//The data row - Contains textfields for Exercise, Weight Type, Weight, Reps, and Notes
		JTextField exerciseField = new JTextField(10);
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 0;       
		c.gridy = currentCol;     
		cPane.add(exerciseField, c);
		exerciseFields.add(exerciseField);

		JTextField weightTypeField = new JTextField(10);
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 1;       
		c.gridy = currentCol;     
		cPane.add(weightTypeField, c);
		weightTypeFields.add(weightTypeField);


		JTextArea weightArea = new JTextArea();
		weightArea.setEditable(false);
		c.fill = GridBagConstraints.HORIZONTAL;
		c.insets = new Insets(1,3,1,3);  //top padding
		c.gridx = 2;       
		c.gridy = currentCol;     
		cPane.add(weightArea, c);

		JTextArea repsArea = new JTextArea();
		c.fill = GridBagConstraints.HORIZONTAL;
		repsArea.setEditable(false);
		c.insets = new Insets(1,3,1,3);  //top padding
		c.gridx = 3;       
		c.gridy = currentCol;     
		cPane.add(repsArea, c);

		JTextArea notesArea = new JTextArea();
		notesArea.setEditable(false);
		c.fill = GridBagConstraints.HORIZONTAL;
		c.insets = new Insets(1,3,1,3);  //top padding
		c.gridx = 4;       
		c.gridy = currentCol;     
		cPane.add(notesArea, c);

		currentCol++;
		frame.validate();

	} 
	
	
	private static void newSaveButtonActionPerformed(java.awt.event.ActionEvent evt) {
		//Needs to read the Exercise field for all unique exercises
		//Needs to read the associated weight type for each unique exercise
		//Search the database for the most recent entry of each exercise-weight type pair
		//Output all results
		Iterator<JTextField> iteratorEF;
		Iterator<JTextField> iteratorWT;
		ResultSet rs;
		Set<String> uniquePair;						//A string representation of each unique pair of exercise and weight type 

		iteratorEF = exerciseFields.iterator();    
		iteratorWT = weightTypeFields.iterator();


		//I need to know all of the unique pairs
		uniquePair = new LinkedHashSet<String>();
		String ef, wtf;

		System.out.println( "Exercise-WeightType-Weight-Date");
		try {
			while (iteratorEF.hasNext()){
				while (iteratorWT.hasNext()){
					ef = iteratorEF.next().getText();
					wtf = iteratorWT.next().getText();

					if( !uniquePair.add(ef+"#"+wtf)){
						System.out.println("A duplicate pair!");
					}
				}
			}

			Iterator<String> iteratorUP = uniquePair.iterator();
			while(iteratorUP.hasNext()){
				//Separate the exercise and weight type strings
				ef = iteratorUP.next();
				wtf = ef.substring(ef.indexOf('#')+1);
				ef = ef.substring(0, ef.indexOf('#'));


				//Get the most recent date of that exercise using that weight type
				rs = conn.executeCurrentStatement("SELECT max(`date`) FROM weightlifting " +
						"where exercise='" + ef + "' and `weight type`='" + wtf + "' order by `Date`");

				rs.next();
				Date date = rs.getDate("max(`date`)");

				//Get the exercise, weight type, and weight for the exercise
				rs = conn.executeCurrentStatement("SELECT exercise, `weight type`, weight from weightlifting" +
						" where exercise='" + ef + "'and `weight type`='" + wtf + "' and `Date` = '" + date.toString()+ 
				"' order by `Order`");


				System.out.println( "---------------------------------");
				//Output the previous exercises
				while(rs.next()){
					String ex = rs.getString("Exercise");
					String wt = rs.getString("Weight Type");
					String w = rs.getString("Weight");

					System.out.println( ex + "-" + wt + "-" + w + "-" + date.toString() );
				}//end while loop

			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println("Save button pressed");
		
	} 


	/**
	 * @param pane
	 */
	public static void addComponentsToPane(Container pane) {
		if (RIGHT_TO_LEFT) {
			cPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		}
		cPane.setLayout(new GridBagLayout());
		cPane.setSize(750, 500);
		GridBagConstraints c = new GridBagConstraints();


		//The title row
		Font titleFont = new Font(Font.SERIF, Font.BOLD, 14);
		JLabel titleLabel = new JLabel("TODAY'S WORKOUT");
		titleLabel.setFont(titleFont);
		c.anchor = GridBagConstraints.NORTH;
		c.gridy = 0;
		c.gridx = 2;
		cPane.add(titleLabel, c);

		//The Shared data row - Contains Date and Location variables
		Font sharedFont = new Font(Font.SERIF, Font.PLAIN, 12);
		//Date should be selected in constructor
		JLabel dateLabel = new JLabel(new java.text.SimpleDateFormat("yyyy/MM/dd").format(new java.util.Date()));
		dateLabel.setFont(sharedFont);
		c.anchor = GridBagConstraints.NORTH;
		c.gridy = 1;
		c.gridx = 1;
		cPane.add(dateLabel, c);

		JLabel locationLabel = new JLabel("Workout Location");
		//Location should be selected in constructor
		locationLabel.setFont(sharedFont);
		c.anchor = GridBagConstraints.NORTH;
		c.gridy = 1;
		c.gridx = 3;
		cPane.add(locationLabel, c);

		//The field row - Contains labels for Exercise, Weight Type, Weight, Reps, and Notes
		Font fieldFont = new Font(Font.SERIF, Font.PLAIN, 12);
		JLabel exerciseLabel = new JLabel("Exercise");
		exerciseLabel.setSize(20, 12);
		//exerciseLabel.setFont(fieldFont);
		c.anchor = GridBagConstraints.NORTH;
		c.weightx = 0.5;
		c.gridx = 0;
		c.gridy = 2;
		cPane.add(exerciseLabel, c);

		JLabel weightTypeLabel = new JLabel("Weight Type");
		//exerciseLabel.setFont(fieldFont);
		c.anchor = GridBagConstraints.NORTH;
		c.weightx = 0.5;
		c.gridx = 1;
		c.gridy = 2;
		cPane.add(weightTypeLabel, c);

		JLabel weightLabel = new JLabel("Weight");
		//exerciseLabel.setFont(fieldFont);
		c.anchor = GridBagConstraints.NORTH;
		c.weightx = 0.5;
		c.gridx = 2;
		c.gridy = 2;
		cPane.add(weightLabel, c);

		JLabel repsLabel = new JLabel("Reps");
		//exerciseLabel.setFont(fieldFont);
		c.anchor = GridBagConstraints.NORTH;
		c.weightx = 0.5;
		c.gridx = 3;
		c.gridy = 2;
		cPane.add(repsLabel, c);

		JLabel notesLabel = new JLabel("           Notes           ");
		notesLabel.setSize(20, 12);
		//exerciseLabel.setFont(fieldFont);
		c.anchor = GridBagConstraints.NORTH;
		c.weightx = 0.5;
		c.gridx = 4;
		c.gridy = 2;
		cPane.add(notesLabel, c);




		//The data row - Contains textfields for Exercise, Weight Type, Weight, Reps, and Notes
		JTextField exerciseField = new JTextField(10);
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 0;       
		c.gridy = 3;     
		cPane.add(exerciseField, c);
		exerciseFields.add(exerciseField);

		JTextField weightTypeField = new JTextField(10);
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 1;       
		c.gridy = 3;     
		cPane.add(weightTypeField, c);
		weightTypeFields.add(weightTypeField);

		JTextArea weightArea = new JTextArea();
		weightArea.setEditable(false);
		c.fill = GridBagConstraints.HORIZONTAL;
		c.insets = new Insets(1,3,1,3);  //top padding
		c.gridx = 2;       
		c.gridy = 3;     
		cPane.add(weightArea, c);

		JTextArea repsArea = new JTextArea();
		repsArea.setEditable(false);
		c.fill = GridBagConstraints.HORIZONTAL;
		c.insets = new Insets(1,3,1,3);  //top padding
		c.gridx = 3;       
		c.gridy = 3;     
		cPane.add(repsArea, c);

		JTextArea notesArea = new JTextArea();
		notesArea.setEditable(false);
		notesArea.setSize(25, 12);
		c.fill = GridBagConstraints.HORIZONTAL;
		c.insets = new Insets(1,3,1,3);  //top padding
		c.gridx = 4;       
		c.gridy = 3;     
		cPane.add(notesArea, c);

		//My add new row button - Not Sure where to place this
		JButton newExerciseButton = new JButton();
		newExerciseButton.setText("+");
		newExerciseButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				newExerciseButtonActionPerformed(evt);
			}
		});
		//c.fill = GridBagConstraints.HORIZONTAL;
		c.ipady = 0;       //reset to default
		c.insets = new Insets(10,10,10,10);  //top padding
		currentCol = 4;
		c.gridx = 4;       //aligned with button 2
		c.gridy = 0;       //third row

		cPane.add(newExerciseButton, c);

		//My save button - Not Sure where to place this
		JButton newSaveButton = new JButton();
		newSaveButton.setText("Save");
		newSaveButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				newSaveButtonActionPerformed(evt);
			}
		});
		//c.fill = GridBagConstraints.HORIZONTAL;
		c.ipady = 0;       //reset to default
		//c.anchor = GridBagConstraints.PAGE_END; //bottom of space
		//c.insets = new Insets(10,0,0,0);  //top padding
		currentCol = 4;
		c.gridx = 0;       //aligned with button 2
		//c.gridwidth = 2;   //2 columns wide
		c.gridy = 0;       //third row

		cPane.add(newSaveButton, c);

	}

	/**
	 * Create the GUI and show it.  For thread safety,
	 * this method should be invoked from the
	 * event-dispatching thread.
	 */
	private static void createAndShowGUI() {
		//Create and set up the window.
		frame = new JFrame("GridBagLayoutDemo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(750, 500);

		//Create a scrollpane named cPane
		cPane = new JPanel();
		frame.getContentPane().add(new JScrollPane(cPane));

		//Add cPane to the contentPane
		addComponentsToPane(cPane);

		//Display the window.
		//frame.pack();
		frame.setVisible(true);
	}

	public static void main(String[] args) {
		//Schedule a job for the event-dispatching thread:
		//creating and showing this application's GUI.
		conn = new DB_connection();
		System.out.println("Testing the basic gui frame.");

		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createAndShowGUI();
			}
		});
	}
}
